#include <iostream>
#include <cstring>
#include <string>

#include "include/itemslist.h"
#include "include/utils.h"

#include "include/ui/mainwindow.h"

using namespace std;

int main(int argc, char *argv[]) {
	if (argc == 1 || argv[1] == string("-h")) {
        cout << "ellie\nUsage: Type -S (scripts) / -A (apps) / -C (commands) / -p{S/A/C} / -H (history) key." << endl;
        return 1;
    }

    makeConfigDir();    

	map<string, string> items;
    ItemsList list = ItemsList();
    string firstArgStr = string(argv[1]);

    if (argc > 1 && argv[1] == string("-S")) {
		items = list.getScripts("ellie");
	} else if (argc > 1 && argv[1] == string("-A")) {
		items = list.getApps();
	} else if (argc > 1 && argv[1] == string("-C")) {
		items = list.getCommands();
	} else if (argc > 1 && argv[1] == string("-a")) {
        items = list.getAll();
    } else if (argc > 1 && firstArgStr.find("-p") != firstArgStr.npos) {
        bool includeCommands = false;
        bool includeScripts = false;
        bool includeApps = false;
        if (firstArgStr.find("C") != firstArgStr.npos) 
            includeCommands = true;
        if (firstArgStr.find("S") != firstArgStr.npos)
            includeScripts = true;
        if (firstArgStr.find("A") != firstArgStr.npos) 
            includeApps = true;
        items = list.getPart(includeCommands, includeScripts, includeApps);
    } else if (argc > 1 && argv[1] == string("-H")) {
        items = list.getHistory();
    }

	vector<string> execs;
	for (auto &exec : items) {
		execs.push_back(exec.first);
	}

	MainWindow *mw = new MainWindow(execs);

	vector<string> result = mw->initWindow();

    string name = result[0];
    string args = "";
    string terminalCommand = "";
    if (result[0].length() < result[1].length()) {
        vector<string> out;
        splitCommand(result[1], out);
        args = out[1];

        out.clear();
        split(args, '|', out);
        if (out[0] == "t") {
            args = "";
            terminalCommand = getTerminal() + " -e ";
        }
        else if (out.size() > 1 && out[1] == "t") {
            args = out[0];
            terminalCommand = getTerminal() + " -e "; 
        }
    }

    string exec = terminalCommand + items[name] + " " + args; 

    if (!exec.empty() && exec != " ") { 
        cout << exec << endl;
    }

    addItemToHistory(name, exec); 

	launchApp(exec);

	return 0;
}


